﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpaceShooter.Extensions;
using Microsoft.Xna.Framework;
using SpaceShooter.GameObjects;
using SpaceShooter.Common;

namespace SpaceShooter.Components
{
    public class MissileManagerComponent : DrawableGameComponent
    {
        private static object locker = new object();
        private static MissileManagerComponent instance;

        private IList<GameObject> bulletList = new List<GameObject>();

        public MissileManagerComponent(Game game)
            :base(game)
        {
            lock (locker)
            {
                if (instance == null)
                    instance = this;
                else
                    throw new Exception("MissileManagerComponent was initialized before!");
            }
        }

        public static void AddMissile(Missile missile)
        {
            instance.bulletList.Add(missile);
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            this.bulletList.Foreach(bullet => bullet.Update(gameTime));

            this.bulletList.RemoveDeadItems(bullet => bullet.RemoveFlag);
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

            if (this.bulletList.Count == 0)
            {
                return;
            }

            var currentScreen = ((BaseGame)this.Game).CurrentScreen;

            this.bulletList.Foreach(o => ModelHelper.DrawGameObject(currentScreen.DefaultCamera, o, s => { }));
        }

        public static IList<GameObject> GetMissileList()
        {
            return instance.bulletList;
        }

        public static void Clear()
        {
            instance.bulletList.RemoveDeadItems(bullet => true);
        }
    }
}
